package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author wy
 * @Date 2021/3/2 10:14
 * @Version 1.0
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        //后面与服务器进行通信 都是用这个通信通道来进行
        Channel c = con.createChannel();
        //定义队列
        c.queueDeclare("helloworld",true,false,false,null);
        //准备好回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到啊傻逼2:"+s);
                //遍历字符串 找到'.' 字符暂停一秒
                for (int i = 0; i < s.length(); i++) {
                    if ('.'==s.charAt(i)){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //参数1.回执数据 2.是否同时确认以前收到的所有信息
                c.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("消息处理完成");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //qos=1 每次收一条 处理完之前不收下一条\
        c.basicQos(1);

        //消费消息
        //第二个参数 自动ack true
        c.basicConsume("helloworld",false,deliverCallback,cancelCallback);
    }

}
